<template>
  <h1>购物车列表</h1>
  <div>
    <!-- 新增全选、全反选操作区 -->
    <div style="margin-bottom: 10px;">
      <el-checkbox v-model="selectAll" @change="handleSelectAll">全选</el-checkbox>
      <el-button type="primary" @click="handleInverseSelect">全反选</el-button>
    </div>
    <div>
      <el-table
          :data="tableData"
          style="width: 100%"
          @selection-change="handleSelectionChange"
          ref="cartTable">      <!-- 新增 ref，用于获取表格实例操作多选框 -->>
      <el-table-column type="selection" width="55" />
      <!-- 其他列定义保持不变 -->
      <el-table-column prop="price" label="商品图片" width="180">
        <template #default="scope">
          <el-image
              style="width: 100px; height: 100px"
              :src="scope.row.goods.image"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              show-progress
              :initial-index="4"
              fit="cover"
          />
        </template>
      </el-table-column>
      <!-- 其余列... -->
      </el-table>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive } from 'vue'
import axios from "axios";
import { useRouter } from 'vue-router'
import { ElTable } from 'element-plus' // 引入 ElTable 类型（若用 TS 可增强类型提示）

const tableData = ref([])
const router = useRouter()
const num = ref(1)
const selectAll = ref(false)
const carts_Ids = ref([])
// 新增表格 ref，用于调用表格 API
const cartTable = ref<InstanceType<typeof ElTable>>()

const handleChange = (value: number | undefined) => {
  console.log(value)
}

// 全反选函数
const handleInverseSelect = () => {
  if (tableData.value.length === 0) return // 无数据直接返回
  tableData.value.forEach((row: any) => {
    // 切换每一行的选中状态
    cartTable.value?.toggleRowSelection(row, !cartTable.value.is_selected(row))
  })
  // 更新全选状态（全反选后，是否全选取决于最后一条数据的选中状态，简单处理可遍历判断，或根据业务需求调整）
  selectAll.value = tableData.value.every((row: any) =>
      cartTable.value?.is_selected(row)
  )
  // 更新选中 ID 集合
  handleSelectionChange(
      tableData.value.filter((row: any) => cartTable.value?.is_selected(row))
  )
}

const getData = () => {
  const token = localStorage.getItem('token') || sessionStorage.getItem('token')
  if (!token) {
    alert('请先登录')
    router.push('/login')
  }
  if (token) {
    axios.get('http://localhost:8000/api/cartDetail/', {
      headers: { 'Authorization': `Bearer ${token}` }
    }).then(res => {
      console.log(res)
      if (res.data.code === 1) {
        tableData.value = res.data.data
      }
    }).catch(err => {
      console.log(err)
      alert('获取购物车列表失败' || err)
    })
  }
}

const handleDelete = (id) => {
  const token = localStorage.getItem('token') || sessionStorage.getItem('token')
  if (!token) {
    alert('请先登录')
    router.push('/login')
  }
  if (token) {
    axios.post(`http://localhost:8000/api/cartDelete/`, { goods_id: id }, {
      headers: { 'Authorization': `Bearer ${token}` }
    }).then(res => {
      console.log(res)
      if (res.data.code === 1) {
        alert('删除成功')
        getData()
      } else {
        alert('删除失败' || res.data.message)
      }
    }).catch(err => {
      alert('删除失败' || err)
    })
  }
}

const handleSelectionChange = (val: any[]) => {
  console.log(val)
  carts_Ids.value = val
  // 全选状态同步：若选中数量等于表格数据总量，视为全选
  selectAll.value = val.length === tableData.value.length
}

// 全选函数（原逻辑补充：若全选，勾选所有；否则取消所有）
const handleSelectAll = () => {
  tableData.value.forEach((row: any) => {
    cartTable.value?.toggleRowSelection(row, selectAll.value)
  })
  // 触发 selection-change 事件更新 carts_Ids
  handleSelectionChange(
      selectAll.value ? tableData.value : []
  )
}

onMounted(() => {
  getData()
})
</script>

<style scoped>

</style>